<?php
/*
 * Created on Sep 10, 2010
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */

require_once('AutoLoader.php');

class Application 
{
	var $__controller;
	var $__model;
	var $__action;
	var $__response;
	var $__request;
	var $__cookie;

	function __construct($controller, $action) 
	{
		AutoLoader::init();
		
		$this->__response = new Response();
		$this->__request = new Request();
		$this->__cookie = new Cookie();
		$this->__controller = $controller == null ? Config::get('default_controller') : $controller . 'Controller';
		$this->__action = $action == null ? Config::get('default_action') : $action;
	}

	function start()
	{		
		ob_start();		
		try {					
			$controller = ClassLoader::load($this->__controller);
			$attributeProcessor = new AttributeProcessor($this->__controller, $this->__action);
			if ((!$attributeProcessor->hasAttributes()) || ($attributeProcessor->hasAttributes() && $attributeProcessor->process())) {
					ClassLoader::invokeMethod($controller, $this->__action);
			} 
		}
		catch (Exception $ex) {
			Log::getLogger(__CLASS__)->error(print_r($ex));
			$this->response->send505();
		}
		ob_flush();		
	}

	function loadView($view, $vars = "")
	{
		try {
			if(is_array($vars) && count($vars) > 0) {
				extract($vars, EXTR_PREFIX_SAME, 'wddx');
			}			
			require_once('application/views/' . $view . '.php');			
		}
		catch (Exception $ex) {
			Log::getLogger(__CLASS__)->error(print_r($ex));
		}
	}

	function loadModel($model, $phpName = null)
	{
		$this->loadClass($model, $phpName);
	}
	
	function loadHelper($helper, $phpName) 
	{	
		$this->loadClass($helper, $phpName);
	}
		
	function loadClass($class, $phpName) 
	{
		try {
			$phpName = $phpName != null ? $phpName : $class;
			$this->$phpName = ClassLoader::load($class);					
		}
		catch (Exception $ex) {
			Log::getLogger(__CLASS__)->error(print_r($ex));
		}	
	}
	
	public function getResponse() 
	{
		return $this->__response;
	}
	
	public function getRequest() 
	{
		return $this->__request;
	}
	
	public function getCookie() {
		return $this->__cookie;
	}
}
?>
